[[...path]].page.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. import React, { useEffect } from 'react';
  2. import { isClient, pagePathUtils, pathUtils } from '@growi/core';
  3. import ExtensibleCustomError from 'extensible-custom-error';
  4. import {
  5. NextPage, GetServerSideProps, GetServerSidePropsContext,
  6. } from 'next';
  7. import dynamic from 'next/dynamic';
  8. import Head from 'next/head';
  9. import { useRouter } from 'next/router';
  10. import { PageAlerts } from '~/components/PageAlert/PageAlerts';
  11. // import { PageComments } from '~/components/PageComment/PageComments';
  12. // import { useTranslation } from '~/i18n';
  13. import { isPopulated } from '~/interfaces/common';
  14. import { CrowiRequest } from '~/interfaces/crowi-request';
  15. // import { renderScriptTagByName, renderHighlightJsStyleTag } from '~/service/cdn-resources-loader';
  16. // import { useIndentSize } from '~/stores/editor';
  17. // import { useRendererSettings } from '~/stores/renderer';
  18. // import { EditorMode, useEditorMode, useIsMobile } from '~/stores/ui';
  19. import { IPageWithMeta } from '~/interfaces/page';
  20. import { ISidebarConfig } from '~/interfaces/sidebar-config';
  21. import { PageModel, PageDocument } from '~/server/models/page';
  22. import { serializeUserSecurely } from '~/server/models/serializers/user-serializer';
  23. import UserUISettings, { UserUISettingsDocument } from '~/server/models/user-ui-settings';
  24. import Xss from '~/services/xss';
  25. import { useSWRxCurrentPage, useSWRxPageInfo, useSWRxPage } from '~/stores/page';
  26. import {
  27. usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth,
  28. } from '~/stores/ui';
  29. import loggerFactory from '~/utils/logger';
  30. // import { isUserPage, isTrashPage, isSharedPage } from '~/utils/path-utils';
  31. // import GrowiSubNavigation from '../client/js/components/Navbar/GrowiSubNavigation';
  32. // import GrowiSubNavigationSwitcher from '../client/js/components/Navbar/GrowiSubNavigationSwitcher';
  33. import { BasicLayout } from '../components/BasicLayout';
  34. import DisplaySwitcher from '../components/Page/DisplaySwitcher';
  35. // import { serializeUserSecurely } from '../server/models/serializers/user-serializer';
  36. // import PageStatusAlert from '../client/js/components/PageStatusAlert';
  37. import {
  38. useCurrentUser, useCurrentPagePath,
  39. useOwnerOfCurrentPage, useIsLatestRevision,
  40. useIsForbidden, useIsNotFound, useIsTrashPage, useShared, useShareLinkId, useIsSharedUser, useIsAbleToDeleteCompletely,
  41. useAppTitle, useSiteUrl, useConfidential, useIsEnabledStaleNotification,
  42. useIsSearchServiceConfigured, useIsSearchServiceReachable, useIsMailerSetup,
  43. useAclEnabled, useIsAclEnabled, useHasSlackConfig, useDrawioUri, useHackmdUri, useMathJax,
  44. useNoCdn, useEditorConfig, useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname, useIsSlackConfigured,
  45. } from '../stores/context';
  46. import { useXss } from '../stores/xss';
  47. import { CommonProps, getServerSideCommonProps, useCustomTitle } from './commons';
  48. // import { useCurrentPageSWR } from '../stores/page';
  49. const logger = loggerFactory('growi:pages:all');
  50. const { isPermalink: _isPermalink, isUsersHomePage, isTrashPage: _isTrashPage } = pagePathUtils;
  51. const { removeHeadingSlash } = pathUtils;
  52. const IdenticalPathPage = (): JSX.Element => {
  53. const IdenticalPathPage = dynamic(() => import('../components/IdenticalPathPage').then(mod => mod.IdenticalPathPage), { ssr: false });
  54. return <IdenticalPathPage />;
  55. };
  56. type Props = CommonProps & {
  57. currentUser: string,
  58. pageWithMetaStr: string,
  59. // pageUser?: any,
  60. // redirectTo?: string;
  61. // redirectFrom?: string;
  62. // shareLinkId?: string;
  63. isLatestRevision?: boolean
  64. isIdenticalPathPage?: boolean,
  65. isForbidden: boolean,
  66. isNotFound: boolean,
  67. // isAbleToDeleteCompletely: boolean,
  68. isSearchServiceConfigured: boolean,
  69. isSearchServiceReachable: boolean,
  70. isSearchScopeChildrenAsDefault: boolean,
  71. isSlackConfigured: boolean,
  72. // isMailerSetup: boolean,
  73. isAclEnabled: boolean,
  74. // hasSlackConfig: boolean,
  75. // drawioUri: string,
  76. // hackmdUri: string,
  77. // mathJax: string,
  78. // noCdn: string,
  79. // highlightJsStyle: string,
  80. // isAllReplyShown: boolean,
  81. // isContainerFluid: boolean,
  82. // editorConfig: any,
  83. isEnabledStaleNotification: boolean,
  84. // isEnabledLinebreaks: boolean,
  85. // isEnabledLinebreaksInComments: boolean,
  86. // adminPreferredIndentSize: number,
  87. // isIndentSizeForced: boolean,
  88. // UI
  89. userUISettings: UserUISettingsDocument | null
  90. // Sidebar
  91. sidebarConfig: ISidebarConfig,
  92. };
  93. const GrowiPage: NextPage<Props> = (props: Props) => {
  94. // const { t } = useTranslation();
  95. const router = useRouter();
  96. const UnsavedAlertDialog = dynamic(() => import('./UnsavedAlertDialog'), { ssr: false });
  97. const { data: currentUser } = useCurrentUser(props.currentUser != null ? JSON.parse(props.currentUser) : null);
  98. // commons
  99. useAppTitle(props.appTitle);
  100. useSiteUrl(props.siteUrl);
  101. useXss(new Xss());
  102. // useEditorConfig(props.editorConfig);
  103. useConfidential(props.confidential);
  104. useCsrfToken(props.csrfToken);
  105. // UserUISettings
  106. usePreferDrawerModeByUser(props.userUISettings?.preferDrawerModeByUser ?? props.sidebarConfig.isSidebarDrawerMode);
  107. usePreferDrawerModeOnEditByUser(props.userUISettings?.preferDrawerModeOnEditByUser);
  108. useSidebarCollapsed(props.userUISettings?.isSidebarCollapsed ?? props.sidebarConfig.isSidebarClosedAtDockMode);
  109. useCurrentSidebarContents(props.userUISettings?.currentSidebarContents);
  110. useCurrentProductNavWidth(props.userUISettings?.currentProductNavWidth);
  111. // page
  112. useCurrentPagePath(props.currentPathname);
  113. useIsLatestRevision(props.isLatestRevision);
  114. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  115. useIsForbidden(props.isForbidden);
  116. useIsNotFound(props.isNotFound);
  117. // useIsTrashPage(_isTrashPage(props.currentPagePath));
  118. // useShared();
  119. // useShareLinkId(props.shareLinkId);
  120. // useIsAbleToDeleteCompletely(props.isAbleToDeleteCompletely);
  121. useIsSharedUser(false); // this page cann't be routed for '/share'
  122. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  123. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  124. useIsSearchServiceReachable(props.isSearchServiceReachable);
  125. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  126. useIsSlackConfigured(props.isSlackConfigured);
  127. // useIsMailerSetup(props.isMailerSetup);
  128. useIsAclEnabled(props.isAclEnabled);
  129. // useHasSlackConfig(props.hasSlackConfig);
  130. // useDrawioUri(props.drawioUri);
  131. // useHackmdUri(props.hackmdUri);
  132. // useMathJax(props.mathJax);
  133. // useNoCdn(props.noCdn);
  134. // useIndentSize(props.adminPreferredIndentSize);
  135. // useRendererSettings({
  136. // isEnabledLinebreaks: props.isEnabledLinebreaks,
  137. // isEnabledLinebreaksInComments: props.isEnabledLinebreaksInComments,
  138. // adminPreferredIndentSize: props.adminPreferredIndentSize,
  139. // isIndentSizeForced: props.isIndentSizeForced,
  140. // });
  141. // const { data: editorMode } = useEditorMode();
  142. let pageWithMeta: IPageWithMeta | undefined;
  143. if (props.pageWithMetaStr != null) {
  144. pageWithMeta = JSON.parse(props.pageWithMetaStr) as IPageWithMeta;
  145. }
  146. useCurrentPageId(pageWithMeta?.data._id);
  147. useSWRxCurrentPage(undefined, pageWithMeta?.data); // store initial data
  148. // useSWRxPage(pageWithMeta?.data._id);
  149. useSWRxPageInfo(pageWithMeta?.data._id, undefined, pageWithMeta?.meta); // store initial data
  150. useIsTrashPage(_isTrashPage(pageWithMeta?.data.path ?? ''));
  151. useCurrentPagePath(pageWithMeta?.data.path);
  152. useCurrentPathname(props.currentPathname);
  153. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  154. useEffect(() => {
  155. if (isClient() && window.location.pathname !== props.currentPathname) {
  156. router.replace(props.currentPathname, undefined, { shallow: true });
  157. }
  158. }, [props.currentPathname, router]);
  159. const classNames: string[] = [];
  160. // switch (editorMode) {
  161. // case EditorMode.Editor:
  162. // classNames.push('on-edit', 'builtin-editor');
  163. // break;
  164. // case EditorMode.HackMD:
  165. // classNames.push('on-edit', 'hackmd');
  166. // break;
  167. // }
  168. // if (props.isContainerFluid) {
  169. // classNames.push('growi-layout-fluid');
  170. // }
  171. // if (page == null) {
  172. // classNames.push('not-found-page');
  173. // }
  174. return (
  175. <>
  176. <Head>
  177. {/*
  178. {renderScriptTagByName('drawio-viewer')}
  179. {renderScriptTagByName('mathjax')}
  180. {renderScriptTagByName('highlight-addons')}
  181. {renderHighlightJsStyleTag(props.highlightJsStyle)}
  182. */}
  183. </Head>
  184. {/* <BasicLayout title={useCustomTitle(props, t('GROWI'))} className={classNames.join(' ')}> */}
  185. <BasicLayout title={useCustomTitle(props, 'GROWI')} className={classNames.join(' ')}>
  186. <header className="py-0">
  187. {/* <GrowiSubNavigation /> */}
  188. GrowiSubNavigation
  189. </header>
  190. <div className="d-edit-none">
  191. {/* <GrowiSubNavigationSwitcher /> */}
  192. GrowiSubNavigationSwitcher
  193. </div>
  194. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  195. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  196. <div id="main" className={`main ${isUsersHomePage(props.currentPathname) && 'user-page'}`}>
  197. <div className="row">
  198. <div className="col">
  199. <div id="content-main" className="content-main grw-container-convertible">
  200. { props.isIdenticalPathPage && <IdenticalPathPage /> }
  201. { !props.isIdenticalPathPage && (
  202. <>
  203. <PageAlerts />
  204. { props.isForbidden
  205. ? <>ForbiddenPage</>
  206. : <DisplaySwitcher />
  207. }
  208. <div id="page-editor-navbar-bottom-container" className="d-none d-edit-block"></div>
  209. {/* <PageStatusAlert /> */}
  210. PageStatusAlert
  211. </>
  212. ) }
  213. </div>
  214. </div>
  215. {/* <div className="col-xl-2 col-lg-3 d-none d-lg-block revision-toc-container">
  216. <div id="revision-toc" className="revision-toc mt-3 sps sps--abv" data-sps-offset="123">
  217. <div id="revision-toc-content" className="revision-toc-content"></div>
  218. </div>
  219. </div> */}
  220. </div>
  221. </div>
  222. <footer>
  223. {/* <PageComments /> */}
  224. PageComments
  225. </footer>
  226. <UnsavedAlertDialog />
  227. </BasicLayout>
  228. </>
  229. );
  230. };
  231. function getPageIdFromPathname(currentPathname: string): string | null {
  232. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  233. }
  234. class MultiplePagesHitsError extends ExtensibleCustomError {
  235. pagePath: string;
  236. constructor(pagePath: string) {
  237. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  238. this.pagePath = pagePath;
  239. }
  240. }
  241. async function getPageData(context: GetServerSidePropsContext, props: Props): Promise<IPageWithMeta|null> {
  242. const req: CrowiRequest = context.req as CrowiRequest;
  243. const { crowi } = req;
  244. const { revisionId } = req.query;
  245. const Page = crowi.model('Page') as PageModel;
  246. const { pageService } = crowi;
  247. const { currentPathname } = props;
  248. const pageId = getPageIdFromPathname(currentPathname);
  249. const isPermalink = _isPermalink(currentPathname);
  250. const { user } = req;
  251. // check whether the specified page path hits to multiple pages
  252. if (!isPermalink) {
  253. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  254. if (count > 1) {
  255. throw new MultiplePagesHitsError(currentPathname);
  256. }
  257. }
  258. const result: IPageWithMeta = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  259. const page = result?.data as unknown as PageDocument;
  260. // populate & check if the revision is latest
  261. if (page != null) {
  262. page.initLatestRevisionField(revisionId);
  263. await page.populateDataToShowRevision();
  264. props.isLatestRevision = page.isLatestRevision();
  265. }
  266. return result;
  267. }
  268. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props, pageWithMeta: IPageWithMeta|null): Promise<void> {
  269. const req: CrowiRequest = context.req as CrowiRequest;
  270. const { crowi } = req;
  271. const Page = crowi.model('Page') as PageModel;
  272. const { currentPathname } = props;
  273. const pageId = getPageIdFromPathname(currentPathname);
  274. const isPermalink = _isPermalink(currentPathname);
  275. const page = pageWithMeta?.data;
  276. if (props.isIdenticalPathPage) {
  277. // TBD
  278. }
  279. else if (page == null) {
  280. props.isNotFound = true;
  281. // check the page is forbidden or just does not exist.
  282. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  283. props.isForbidden = count > 0;
  284. }
  285. else {
  286. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  287. if (isPermalink && page.isEmpty) {
  288. props.currentPathname = page.path;
  289. }
  290. // /path/to/page ==> /62a88db47fed8b2d94f30000
  291. if (!isPermalink && !page.isEmpty) {
  292. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  293. if (!isToppage) {
  294. props.currentPathname = `/${page._id}`;
  295. }
  296. }
  297. }
  298. }
  299. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  300. // const req: CrowiRequest = context.req as CrowiRequest;
  301. // const { crowi } = req;
  302. // const UserModel = crowi.model('User');
  303. // if (isUserPage(props.currentPagePath)) {
  304. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  305. // if (user != null) {
  306. // props.pageUser = JSON.stringify(user.toObject());
  307. // }
  308. // }
  309. // }
  310. async function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): Promise<void> {
  311. const req: CrowiRequest = context.req as CrowiRequest;
  312. const { crowi } = req;
  313. const {
  314. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  315. } = crowi;
  316. props.isSearchServiceConfigured = searchService.isConfigured;
  317. props.isSearchServiceReachable = searchService.isReachable;
  318. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  319. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  320. // props.isMailerSetup = mailService.isMailerSetup;
  321. props.isAclEnabled = aclService.isAclEnabled();
  322. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  323. // props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  324. // props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  325. // props.mathJax = configManager.getConfig('crowi', 'app:mathJax');
  326. // props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  327. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  328. // props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  329. // props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  330. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  331. // props.isEnabledLinebreaks = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks');
  332. // props.isEnabledLinebreaksInComments = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments');
  333. // props.editorConfig = {
  334. // upload: {
  335. // image: crowi.fileUploadService.getIsUploadable(),
  336. // file: crowi.fileUploadService.getFileUploadEnabled(),
  337. // },
  338. // };
  339. // props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  340. // props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  341. props.sidebarConfig = {
  342. isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
  343. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  344. };
  345. }
  346. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  347. const req: CrowiRequest = context.req as CrowiRequest;
  348. const { crowi, user } = req;
  349. const { revisionId } = req.query;
  350. const result = await getServerSideCommonProps(context);
  351. // check for presence
  352. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  353. if (!('props' in result)) {
  354. throw new Error('invalid getSSP result');
  355. }
  356. const props: Props = result.props as Props;
  357. let pageWithMeta;
  358. try {
  359. pageWithMeta = await getPageData(context, props);
  360. props.pageWithMetaStr = JSON.stringify(pageWithMeta);
  361. }
  362. catch (err) {
  363. if (err instanceof MultiplePagesHitsError) {
  364. props.isIdenticalPathPage = true;
  365. }
  366. else {
  367. throw err;
  368. }
  369. }
  370. injectRoutingInformation(context, props, pageWithMeta);
  371. injectServerConfigurations(context, props);
  372. if (user != null) {
  373. props.currentUser = JSON.stringify(user);
  374. }
  375. // UI
  376. const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
  377. props.userUISettings = JSON.parse(JSON.stringify(userUISettings));
  378. return {
  379. props,
  380. };
  381. };
  382. export default GrowiPage;